
# Create your views here.
import json
import os

from django.db.models import Count
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .models import *


def every(request):
    return render(request, 'login.html')


import subprocess
from django.http import JsonResponse

def start_crawler(request):
    try:
        # 获取 current_weather.py 所在的目录
        script_dir = os.path.dirname(os.path.abspath('spider\\current_weather.py'))
        # 调用 current_weather.py 脚本
        subprocess.Popen(['python', 'current_weather.py'], cwd=script_dir)
        return JsonResponse({'status': 'success', 'message': '爬虫已启动'})
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)})


# def start_crawler(request):
#     try:
#         # 获取 current_weather.py 所在的目录
#         script_dir = os.path.dirname(os.path.abspath('spider\\current_weather.py'))
#
#         # 调用 current_weather.py 脚本
#         result = subprocess.run(['python', 'current_weather.py'], cwd=script_dir, capture_output=True, text=True)
#         if result.returncode == 0:
#             return JsonResponse({'status': 'success', 'message': '爬虫已成功完成'})
#         else:
#             return JsonResponse({'status': 'error', 'message': result.stderr})
#     except Exception as e:
#         return JsonResponse({'status': 'error', 'message': str(e)})
# 登录
@csrf_exempt
def login(request):
    if request.method == 'POST':
        try:
            # 解析 JSON 数据
            data = json.loads(request.body)
            email = data.get('email')
            password = data.get('password')
            try:
                user = Manager.objects.get(email=email, password=password)
                request.session['email'] = email
                # 返回用户详细信息
                user_info = {
                    'id': user.id,
                    'email': user.email,
                    'username': user.username , # 假设 Manager 模型中有 username 字段
                    'phone_number': user.phone_number,
                    'address': user.address,
                    'birthday': user.birthday,
                    'created_at': user.created_at,
                    'password': user.password
                }
                return JsonResponse({'message': '登录成功','user': user_info})
            except Manager.DoesNotExist:
                return JsonResponse({'message': '账号或密码错误'}, status=400)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的 JSON 数据'}, status=400)
    return JsonResponse({'message': '无效的请求方法'}, status=405)

# 注册
@csrf_exempt
def register(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data.get('username')
            email = data.get('email')
            password = data.get('password')

            if Manager.objects.filter(username=username).exists():
                return JsonResponse({'message': '该用户名已被注册'}, status=400)

            if Manager.objects.filter(email=email).exists():
                return JsonResponse({'message': '该邮箱已被注册'}, status=400)

            Manager.objects.create(username=username, email=email,password=password)
            return JsonResponse({'message': '注册成功'})
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的 JSON 数据'}, status=400)
    return JsonResponse({'message': '无效的请求方法'}, status=405)


# 修改用户信息
@csrf_exempt
def update_user_info(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print('接收到的数据:', data)  # 添加日志输出
            username = data.get('username')
            phone_number = data.get('phone_number')
            address = data.get('address')
            birthday = data.get('birthday')

            email = data.get('email')  # 直接从请求数据中获取 email
            print('获取到的 email:', email)  # 添加日志输出


            if not email:
                return JsonResponse({'message': '未获取到用户 email'}, status=400)

            try:
                user = Manager.objects.get(email=email)
                if username:
                    user.username = username
                if phone_number:
                    user.phone_number = phone_number
                if address:
                    user.address = address
                if birthday:
                    # 处理日期格式
                    from datetime import datetime
                    try:
                        birthday_date = datetime.fromisoformat(birthday.replace('Z', '+00:00'))
                        user.birthday = birthday_date
                    except ValueError:
                        return JsonResponse({'message': '日期格式错误'}, status=400)
                user.save()
                return JsonResponse({'message': '更新成功'})
            except Manager.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=400)
        except json.JSONDecodeError:
            print('JSON 解析错误:', request.body)  # 添加日志输出
            return JsonResponse({'message': '无效的 JSON 数据'}, status=400)
    return JsonResponse({'message': '无效的请求方法'}, status=405)

# 修改密码
@csrf_exempt
def change_password(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            old_password = data.get('oldPassword')
            new_password = data.get('newPassword')

            # email = request.session.get('email')
            email = data.get('email')  # 直接从请求数据中获取 email
            print('获取到的 email:', email)  # 添加日志输出
            if not email:
                return JsonResponse({'message': '未获取到用户 email'}, status=400)

            try:
                user = Manager.objects.get(email=email)
                if user.password != old_password:
                    return JsonResponse({'message': '原密码输入错误'}, status=400)

                # 更新用户密码
                user.password = new_password
                user.save()
                return JsonResponse({'message': '密码修改成功'})
            except Manager.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=400)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的 JSON 数据'}, status=400)
    return JsonResponse({'message': '无效的请求方法'}, status=405)


'''天气概况'''
@csrf_exempt
def condition(request):
    email = request.session.get('email')

    sunny, cloudy, rainy, snowy = count_weather()
    highest_temperatures, lowest_temperatures = highest_lowest_temperature()
    highest_wind, highest_humidity = highest_wind_humidity()

    print(sunny, cloudy, rainy, snowy)
    print(highest_temperatures, lowest_temperatures)
    print("风速最大：",highest_wind,'湿度最大：', highest_humidity)

    # 返回JSON格式的数据
    return JsonResponse({
        'email': email,
        'sunny': sunny,
        'cloudy': cloudy,
        'rainy': rainy,
        'snowy': snowy,
        'highest_temperatures': list(highest_temperatures),
        'lowest_temperatures': list(lowest_temperatures),
        'highest_wind': list(highest_wind),
        'highest_humidity': list(highest_humidity),
    })

def count_weather():
    cloudy_cities = WeatherData.objects.filter(天气情况__contains='阴').count()
    sunny_cities = WeatherData.objects.filter(天气情况__contains='晴').count()
    rainy_cities = WeatherData.objects.filter(天气情况__contains='雨').count()
    snowy_cities = WeatherData.objects.filter(天气情况__contains='雪').count()

    return sunny_cities, cloudy_cities, rainy_cities, snowy_cities

def highest_lowest_temperature():
    highest_temperatures = WeatherData.objects.order_by('-温度').values('城市', '温度')[:10]
    lowest_temperatures = WeatherData.objects.order_by('温度').values('城市', '温度')[:10]

    return highest_temperatures, lowest_temperatures


def highest_wind_humidity():
    highest_wind = WeatherData.objects.order_by('-风速').values('城市', '风速')[:10]
    highest_humidity = WeatherData.objects.order_by('-湿度').values('城市', '湿度')[:10]

    return highest_wind, highest_humidity



'''用户管理'''
@csrf_exempt
def list_all_users(request):
    if request.method == 'GET':
        try:
            # 查询所有用户信息
            users = User.objects.all()
            user_list = []
            for user in users:
                user_info = {
                    'id': user.id,
                    'username': user.username,
                    'password': user.password,
                    'email': user.email,
                    'phone_number': user.phone_number,
                    'address': user.address,
                    'birthday': user.birthday,
                    'created_at': user.created_at
                }
                user_list.append(user_info)
            return JsonResponse({'data': user_list}, status=200)
        except Exception as e:
            return JsonResponse({'message': str(e)}, status=500)
    else:
        return JsonResponse({'message': '无效的请求方法'}, status=405)

# 查询用户
@csrf_exempt
def get_user_by_email(request):
    if request.method == 'GET':
        email = request.GET.get('email')
        if email:
            try:
                user = User.objects.get(email=email)
                user_info = {
                    'id': user.id,
                    'username': user.username,
                    'password': user.password,
                    'email': user.email,
                    'phone_number': user.phone_number,
                    'address': user.address,
                    'birthday': user.birthday,
                    'created_at': user.created_at
                }
                return JsonResponse({'status': 200, 'user': user_info})
            except User.DoesNotExist:
                return JsonResponse({'status': 404, 'message': '用户不存在'}, status=404)
        else:
            return JsonResponse({'status': 400, 'message': '未提供用户邮箱'}, status=400)
    else:
        return JsonResponse({'message': '无效的请求方法'}, status=405)

# 删除用户
@csrf_exempt
def delete_user(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_id = data.get('id')

            if not user_id:
                return JsonResponse({'message': '未提供用户 ID'}, status=400)

            try:
                user = User.objects.get(id=user_id)
                user.delete()
                return JsonResponse({'message': '用户删除成功'})
            except User.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=400)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的 JSON 数据'}, status=400)
    return JsonResponse({'message': '无效的请求方法'}, status=405)

# 当天天气查询
@csrf_exempt
def get_weather_details(request):
    if request.method == 'GET':
#         根据前端传来的城市
        city_data= request.GET.get('city')
        if city_data:
            try:
                dataInfo=WeatherData.objects.get(城市=city_data)
                weatherInfo={
                    'city': dataInfo.城市,
                    'temp': dataInfo.温度,
                    'body_temp': dataInfo.体感温度,
                    'wind_speed': dataInfo.风速,
                    'wind': dataInfo.风向,
                    'windlevel': dataInfo.风向,
                    'pressure': dataInfo.大气压强,
                    'weather': dataInfo.天气情况,
                    'Angle':dataInfo.风向角度,
                    'humidity': dataInfo.湿度,
                    'visibility': dataInfo.能见度
                }
                print(weatherInfo)
                return JsonResponse({'status':200,'data':weatherInfo})
            except WeatherData.DoesNotExist:
                return JsonResponse({'status':404, 'message': '不存在'}, status=404)
        else:
            return JsonResponse({'status':400, 'message': '该城市不存在'}, status=400)




# @csrf_exempt
# def get_weather_data(request):
#     if request.method == 'POST':
#         # 获取前端传来的城市名和年月
#         data = json.loads(request.body)
#         city_name = data.get('city')
#         year_month = data.get('year_month')
#         if not city_name or not year_month:
#             return JsonResponse({'error': '缺少必要参数'}, status=400)
#         # 根据城市名和年月过滤数据
#         weather_data = LishiWeather.objects.filter(city=city_name, 日期__startswith=year_month)
#         # 提取最高温度、最低温度和风向风级数据
#         highest_temps = [weather.最高温度 for weather in weather_data if weather.最高温度 is not None]
#         lowest_temps = [weather.最低温度 for weather in weather_data if weather.最低温度 is not None]
#         wind_levels = []
#         for weather in weather_data:
#             if weather.风向 is not None:
#                 # 按“风”字将风向数据拆分为风向和风级两部分
#                 parts = weather.风向.split('风')
#                 if len(parts) == 2:
#                     try:
#                         wind_level = int(parts[1].strip().rstrip('级'))
#                         wind_levels.append(wind_level)
#                     except ValueError:
#                         # 处理风级转换异常，可根据实际需求修改
#                         pass
#
#         # 统计每个风力等级的数量
#         wind_level_counts = {}
#         for level in range(1, 6):
#             wind_level_counts[level] = wind_levels.count(level)
#
#         # 构造返回数据
#         response_data = {
#             'highest_temps': highest_temps,
#             'lowest_temps': lowest_temps,
#             'wind_level_counts': wind_level_counts
#         }
#         print(response_data)
#         return JsonResponse(response_data)
#     return JsonResponse({'error': '不支持的请求方法'}, status=405)



'''首页'''
@csrf_exempt
def home(request):
    email = request.session.get('email')

    # 调用统计函数
    cities_count, weather_data_count, users_count ,manager_count= count_cities_weather_users()

    print(cities_count, weather_data_count, users_count,manager_count)

    # 返回JSON格式的数据
    return JsonResponse({
        'email': email,
        'cities_count': cities_count,
        'weather_data_count': weather_data_count,
        'users_count': users_count,
        'manager_count': manager_count
    })


# 统计城市数量、天气数据数量和用户数量
def count_cities_weather_users():
    # 统计不重复的城市数量
    cities_count = WeatherData.objects.values('城市').distinct().count()
    # 统计天气数据数量
    weather_data_count = WeatherData.objects.count()
    # 统计用户数量
    users_count = User.objects.count()
    manager_count=Manager.objects.count()

    return cities_count, weather_data_count, users_count, manager_count





# 获取城市天气数据
def city_tem(data):
    # 获取所有的天气数据，使用 values_list 只取需要的字段
    city_weather_data = WeatherData.objects.values_list('城市', '温度', '体感温度', '天气情况', '风力等级', '湿度', '能见度')

    # 手动创建省份城市的列表
    province_cities = {
        '北京市': '北京',
        '天津市': '天津',
        '河北省': '石家庄',
        '山西省': '太原',
        '内蒙古自治区': '呼和浩特',
        '辽宁省': '沈阳',
        '吉林省': '长春',
        '黑龙江省': '哈尔滨',
        '上海市': '上海',
        '江苏省': '南京',
        '浙江省': '杭州',
        '安徽省': '合肥',
        '福建省': '福州',
        '江西省': '南昌',
        '山东省': '济南',
        '河南省': '郑州',
        '湖北省': '武汉',
        '湖南省': '长沙',
        '广东省': '广州',
        '广西壮族自治区': '南宁',
        '海南省': '海口',
        '重庆市': '重庆',
        '四川省': '成都',
        '贵州省': '贵阳',
        '云南省': '昆明',
        '西藏自治区': '拉萨',
        '陕西省': '西安',
        '甘肃省': '兰州',
        '青海省': '西宁',
        '宁夏回族自治区': '银川',
        '新疆维吾尔自治区': '乌鲁木齐',
        '台湾省': '台北',
        '香港特别行政区': '香港',
        '澳门特别行政区': '澳门',
    }

    province_weather_data = {}
    for province, cities in province_cities.items():
        for city_data in city_weather_data:
            city = city_data[0]
            if city in cities:
                province_weather_data[province] = {
                    '温度': city_data[1],
                    '体感温度': city_data[2],
                    '天气情况': city_data[3],
                    '风力等级': city_data[4],
                    '湿度': city_data[5],
                    '能见度': city_data[6]
                }
                break


    return province_weather_data




# 地图视图
@csrf_exempt
def map(request):
    email = request.session.get('email')
    data = request.GET.get('data', '温度')
    temperature = city_tem(data)
    print(temperature)
    # temperature = json.dumps(temperature)
    # print(temperature)


    return JsonResponse({
        'email': email,
        'mapData': temperature,
        'data': data
    })


'''管理员管理'''
# 列举所有管理员信息
@csrf_exempt
def list_all_managers(request):
    if request.method == 'GET':
        try:
            # 查询所有用户信息
            managers = Manager.objects.all()
            manager_list = []
            for manager in managers:
                manager_info = {
                    'id': manager.id,
                    'username': manager.username,
                    'password': manager.password,
                    'email': manager.email,
                    'phone_number': manager.phone_number,
                    'address': manager.address,
                    'birthday': manager.birthday,
                    'created_at': manager.created_at
                }
                manager_list.append(manager_info)
            print(manager_list)
            return JsonResponse({'data': manager_list}, status=200)
        except Exception as e:
            return JsonResponse({'message': str(e)}, status=500)
    else:
        return JsonResponse({'message': '无效的请求方法'}, status=405)


# 按邮箱查询管理员
@csrf_exempt
def get_manager_by_email(request):
    if request.method == 'GET':
        email = request.GET.get('email')
        if email:
            try:
                user = Manager.objects.get(email=email)
                user_info = {
                    'id': user.id,
                    'username': user.username,
                    'password': user.password,
                    'email': user.email,
                    'phone_number': user.phone_number,
                    'address': user.address,
                    'birthday': user.birthday,
                    'created_at': user.created_at
                }
                return JsonResponse({'status': 200, 'user': user_info})
            except Manager.DoesNotExist:
                return JsonResponse({'status': 404, 'message': '用户不存在'}, status=404)
        else:
            return JsonResponse({'status': 400, 'message': '未提供用户邮箱'}, status=400)
    else:
        return JsonResponse({'message': '无效的请求方法'}, status=405)
# 删除管理员
@csrf_exempt
def delete_manager(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_id = data.get('id')

            if not user_id:
                return JsonResponse({'message': '未提供用户 ID'}, status=400)

            try:
                user = Manager.objects.get(id=user_id)
                user.delete()
                return JsonResponse({'message': '管理员删除成功'})
            except Manager.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=400)
        except json.JSONDecodeError:
            return JsonResponse({'message': '无效的 JSON 数据'}, status=400)
    return JsonResponse({'message': '无效的请求方法'}, status=405)


#